ImageGear Java PDF
Merge PDF Documents

To merge two PDF documents:

  1. Use the createDocument method of the PDF class to create two new instances of the Document class (one per PDF file).
  2. Use the openDocument method of the Document class to load the PDF documents.
  3. Use the getPageCount method of the Document class to get the number of pages for the documents.
  4. Use the insertPages methods of the Document class to append all pages (the number of pages retrieved during previous step) from the second PDF document into the first PDF document.
  5. Use the saveDocument method of the Document class to save the resulting PDF document to a file.
  6. Use the close method of the Document class to close the documents if you do not need them anymore.

The following is an illustration of how to merge two PDF documents:

 
Copy Code
import com.accusoft.imagegearpdf.*;

class PdfDemo
{
        private PDF pdf;
        private Document document1;
        private Document document2;
        
        // Merge two PDF documents.
        public void mergeDocuments()
        {
                try
                {
                        // Get page count for both of PDF documents.
                        long pageCount1 =  this.document1.getPageCount();
                        long pageCount2 =  this.document2.getPageCount();
                        
                        // Append all pages of the second document to the first document.
                        this.document1.insertPages(pageCount1, this.document2, 0, pageCount2);
                }
                catch (Throwable ex)
                {
                        // Failed to merge PDF documents.
                        System.err.println("Exception: " + ex.toString());
                }
        }
}

See Also

 

 


©2016. Accusoft Corporation. All Rights Reserved.

Send Feedback